package logic

import (
	"context"
	"errors"
	"fmt"
	"google.golang.org/grpc/stats"
	"jd_srv/cache"
	"jd_srv/models"
	"time"

	"jd_srv/internal/svc"
	"jd_srv/jd"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddCartLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddCartLogic {
	return &AddCartLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddCartLogic) AddCart(in *jd.AddCartRequest) (*jd.AddCartResponse, error) {
	// todo: add your logic here and delete this line

	var err error
	var u models.User
	var g models.Goods
	if err = u.GetUserByID(in.UserId); err != nil {
		logx.Error("获取用户信息失败")
		return nil, errors.New("获取用户信息失败")
	}
	if u.ID == 0 {
		logx.Error("用户不存在")
		return nil, errors.New("用户不存在")
	}
	if err = g.GetGoodsById(in.GoodsId); err != nil {
		logx.Error("获取商品信息失败")
		return nil, errors.New("获取商品信息失败")
	}
	if g.ID == 0 {
		logx.Error("该商品不存在")
		return nil, errors.New("该商品不存在")
	}

	if g.Stock < in.Num {
		logx.Error("商品库存不足")
		return nil, errors.New("商品库存不足")
	}

	_ = stats.Begin{
		Client:                    false,
		BeginTime:                 time.Time{},
		FailFast:                  false,
		IsClientStream:            false,
		IsServerStream:            false,
		IsTransparentRetryAttempt: false,
	}

	if cache.IsExistCart(in.UserId, in.GoodsId) {
		fmt.Println("购物车存在该商品")

		cache.HIncrNum(in.UserId, in.GoodsId, in.Num)
	} else {
		fmt.Println("购物车不存在该商品")
		goodsMap := map[string]interface{}{
			"user_id":     int(in.UserId),
			"goods_id":    int(in.GoodsId),
			"goods_num":   int(in.Num),
			"goods_price": g.Price,
			"goods_name":  g.Title,
		}
		if err = cache.AddCart(in.UserId, in.GoodsId, goodsMap); err != nil {
			logx.Error("<添加入购物车失败>", err)
			return nil, errors.New("添加入购物车失败")
		}
	}

	return &jd.AddCartResponse{}, nil
}
